<?php
namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\AddressAddRequest;
use App\Http\Requests\AvatarUpdateRequest;
use App\Http\Requests\UsernameUpdateRequest;
use App\Http\Requests\GenderUpdateRequest;
use App\Http\Requests\EmailUpdateRequest;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\HouseCostsOrderConfirmRequest;
use App\Http\Requests\HouseCostsOrderCreateRequest;
use App\Http\Requests\ManagerFeedbackRequest;
use App\Http\Requests\PasswordResetRequest;
use App\Libraries\AppPay;
use App\Mail\Basic;
use App\Models\ClientUser;
use App\Models\ClientUserMessagesContent;
use App\Models\ClientUserRoles;
use App\Models\ClientUserAddress;
use App\Models\ClientUserHouse;
use App\Models\ClientUserIntegral;
use App\Models\ClientUserManagerDuty;
use App\Models\ClientUserManagerFeedback;
use App\Models\ClientUserMessage;
use App\Models\ClientUserWorking;
use App\Models\ClientUserMessagesType;
use App\Models\ClientUserRolesHouse;
use App\Models\ClientUserRongcloud;
use App\Models\ClientUserTicket;
use App\Models\Config;
use App\Models\DutyBudding;
use App\Models\House;
use App\Models\HouseDistrict;
use App\Models\HouseDistrictCosts;
use App\Models\NeighborHelp;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class UsercenterController extends CommonController {
	
	public function __construct(){
		parent::__construct();
		// CommonController 里面已经有了 $this->user $this->uid 两个属性了
		$this->check_login();
	}
	
	public function index(){
		$user_house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->pluck('house_id');

		$house_first = $user_house->first();
		
		// 当前房屋绑了多少人
		$house_bind_count = ClientUserHouse::where(['house_id'=>$house_first])->count();
		$houses = ClientUserHouse::select('house.house_id as id','house.house_detail as name_long')
            ->leftJoin('house','client_user_house.house_id','=','house.house_id')
            ->where(['uid'=>$this->uid])
            ->orderBy('primary','desc')
            ->get();
		$house = $houses->first();
		$return = [
			'user'					=> $this->user,
			'house_bind_count'		=> $house_bind_count,
			'house'					=> $house,
			'houses'				=> $houses,
			'message_unview_count'	=> group99(ClientUserMessage::where(['uid'=>$this->uid,'viewed'=>0])->count()),
		];
		return json_success('OK',$return);
	}
//	public function house(){
//        $house_ids = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('primary','desc')->pluck('house_id');
//        $house = House::whereIn('house_id',$house_ids)->get();
//        $return = [
//            'house'					=> $house,
//        ];
//        return json_success('OK',$return);
//    }
	/**
	 * 我的基本信息
	 */
	public function info(Request $request){
		$user = $this->user;
		return json_success('OK',$user);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 多个房产 房屋切换
	 */
	public function house_switch(BasicRequest $request){
		$house_id = $request->input('house_id');

		ClientUserHouse::where(['uid'=>$this->uid])->update(['primary'=>0]);
		$var = ClientUserHouse::where(['house_id'=>$house_id,'uid'=>$this->uid])->update(['primary'=>1]);
		$village_id = ClientUserHouse::select('village_id')->where(['house_id'=>$house_id,'uid'=>$this->uid])->first()['village_id'];

		return json_success('切换完成',['village_id'=>$village_id]);
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 修改头像
	 */
	public function avatar_update(AvatarUpdateRequest $request){
		$avatar = $request->input('avatar',config('basic.avatar'));
		$user = ClientUser::find($this->uid);
		$user->avatar = $avatar;
		$var = $user->save();
		return json_return($var,'',' 头像上传成功');
	}

	/**
	 * @param Request $request
	 * @return array
	 * 修改用户名
	 */
	public function username_update(UsernameUpdateRequest $request){
	    $username = $request->input('username');
	    $user = ClientUser::find($this->uid);
	    $user->username = $username;
	    $var = $user->save();
	    return json_return($var,'','修改昵称成功');
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 修改性别
	 */
	public function gender_update(GenderUpdateRequest $request){
	    $gender = $request->input('gender');
	    $user = ClientUser::find($this->uid);
	    $user->gender = $gender;
	    $var = $user->save();
	    return json_return($var,'','修改性别成功');
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 修改邮箱
	 */
	public function email_update(EmailUpdateRequest $request){
	    $email = $request->input('email');
	    $user = ClientUser::find($this->uid);
	    $user->email = $email;
	    $var = $user->save();
	    return json_return($var,'','修改邮箱成功');
	}

	/**
	 * 我的房产
	 */
	public function house(Request $request){
		$house = ClientUserHouse::where(['uid'=>$this->uid])->orderBy('id','desc')->get()->each(function($v,$k){
			$v->detail();
		});
		return json_success('OK',$house);
	}
	
	// 我的房产待缴费用列表
	public function house_costs_unpaid(Request $request){
		$house_id = $request->input('house_id');
		$data = HouseDistrictCosts::where(['house_id'=>$house_id])->field()->unpaid()->get();
		$data = HouseDistrictCosts::parseList($data);
		return json_success('OK',$data);
	}
	
	// 缴费历史
	public function house_costs_paid(Request $request){
		$house_id = $request->input('house_id');
		$page = $request->input('page',1);
		$page_size = config('basic.page_size');
		$data = HouseDistrictCosts::select(DB::raw('order_no,sum(amount) amount,from_unixtime(pay_time,\'%Y-%m-%d %H:%i:%s\') pay_time,invoice,pay_type'))->where(['house_id'=>$house_id])->paid()->groupBy('order_no')->orderBy('id','desc')->get()->slice(($page-1) * $page_size,$page_size);
		return json_success('OK',$data);
	}
	
	// 缴费历史详情，根据订单号查询
	public function house_costs_detail(Request $request){
		$order_no = $request->input('order_no');
		$detail = HouseDistrictCosts::select(DB::raw(from_unixtime('pay_time').',invoice,pay_type,order_no'))->where(['order_no'=>$order_no])->paid()->first();
		$details = HouseDistrictCosts::field()->where(['order_no'=>$order_no])->paid()->get();
		$detail->details = $details;
		return json_success('OK',$detail);
	}
	
	// 缴费选择支付方式和发票配送方式
	public function house_costs_confirm(HouseCostsOrderConfirmRequest $request){
        return json_error('暂未开通缴费功能');
		$id_in = json_decode($request->input('id'),true);
//		$type_all = HouseDistrictCosts::groupBy('type')->orderBy('type','asc')->pluck('type')->each(function($v,$k) use ($id_in){
//			if(!in_array($v,$id_in)){
//				throw new ApiException('暂不支持单独支付，请选择全部');
//			}
//		});
		$amount = HouseDistrictCosts::whereIn('id',$id_in)->unpaid()->sum('amount');
		$list = HouseDistrictCosts::whereIn('id',$id_in)->unpaid()->field()->get();
		$return = [
			'amount'	=> $amount,
			'list'		=> $list,
			// 发票类型选择，单选
			'invoice_type'	=> config('basic.invoice_type'),
			// 支付方式选择，单选
			'pay_type'	=> config('basic.pay_type'),
		];
		return json_success('OK',$return);
	}
	
	// 缴费支付
	public function house_costs_pay(HouseCostsOrderCreateRequest $request){
        return json_error('暂未开通缴费功能');
		$id_in = json_decode($request->input('id'),true);
		$invoice_type = $request->input('invoice_type');
		$pay_type = $request->input('pay_type');
		$invoice_type_config = array_field(config('basic.invoice_type'),'type');
		$pay_type_config = array_field(config('basic.pay_type'),'type');
		$order_no = HouseDistrictCosts::createOrderNo();
		$update = [
			'order_no'	=> $order_no,
			'invoice'	=> $invoice_type_config[$invoice_type]['name'],
			'pay_type'	=> $pay_type_config[$pay_type]['name'],
		];
		$var = HouseDistrictCosts::whereIn('id',$id_in)->update($update);
		// 生成支付方式
		$list = HouseDistrictCosts::whereIn('id',$id_in)->unpaid()->field()->get();
		$amount = 0;
		$product_name = Config::key('company_name')->value('value') ?? '缴费';
		$notify_url = url('notify/'.$pay_type);
		$list->each(function($v) use(&$amount){
			// 计算支付总金额
			$amount += $v->amount;
		});
		$app = new AppPay();
		$sign = $app->$pay_type($order_no,$product_name,$amount,$notify_url);
		return json_return($var,'','订单创建成功，现跳转支付',['sign'=>$sign]);
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 我的房屋管家，多房产，多管家，一个房产对应一个管家
	 */
	public function house_manager(Request $request){
          $village_id = $request->input('house_id');
		if(!ClientUserHouse::where(['uid'=>$this->uid])->exists()){
			throw new ApiException('请先绑定房屋');
		}
		if($village_id) {
		     //选择小区
               $house_id = ClientUserHouse::where(['uid' => $this->uid, 'village_id' => $village_id])->orderBy('primary', 'desc')->value('house_id');
          }else{
               $house_id = ClientUserHouse::where(['uid' => $this->uid])->orderBy('primary', 'desc')->value('house_id');
          }
		$roles_house=ClientUserRolesHouse::where('house_id',$house_id)->first();
		$manager_uid = $roles_house->uid;
		$manager = ClientUser::select(DB::raw('id uid,username,realname,mobile,avatar,signature,iswork'))->where(['id'=>$manager_uid])->get()->each(function($v,$k) use ($house_id,$manager_uid){
			$v->house_id = $house_id;
			$house = HouseDistrict::find($v->house_id)->detail();
			$v->house = $house->name_long;
			$v->type_name = '管家';
			$roles_house_id = ClientUserRoles::leftJoin('client_user_relationship','client_user_roles.ship_id','=','client_user_relationship.id')
                   ->where('client_user_roles.uid','=',$manager_uid)
                   ->value('house_id');
			$v->work_area = $this->get_manager_area($roles_house_id,$manager_uid);
		});

		$budding_id = House::where('house_id','=',$house_id)->value('budding_id');
		$duty_uid = DutyBudding::where(['budding_id'=>$budding_id,'status'=>1])->value('uid');
          if($duty_uid){
               $check=1;
               foreach ($manager as $key=>$val){
                    if($val['iswork']==1 && $manager_uid == $duty_uid) {
                         $check=0;
                    }
               }
               if($check) {
                    $manager1 = ClientUser::select(DB::raw('id uid,username,realname,mobile,avatar,signature'))->where(['id' => $duty_uid])->first();
                    $manager1->house_id = $house_id;
                    $manager1->iswork = 1;
                    $house = HouseDistrict::find($manager1->house_id)->detail();
                    $manager1->house = $house->name_long;
                    $manager1->type_name = '值班管家';
                    $manager1->work_area = $this->get_manager_area($partition_id, 0);
                    $manager[] = $manager1;
               }
          }

		return json_success('OK',$manager);
	}
     private function get_manager_area($house_id,$uid=0){
          $house = HouseDistrict::select('type')->where('id','=',$house_id)->first();

          $return =[];
          switch ($house->type) {
               case 7:
                    $return=House::select('house.partition_id','house.village_id','house_district.name as name_long')
                        ->where(['partition_id'=>$house_id])->groupBy('budding_id')
                        ->leftJoin('house_district','house_district.id','=','house.budding_id')
                        ->when($uid,function($query) use($uid){
                             $query->leftJoin('client_user_roles_house as roles','roles.house_id','=','house_district.id')->where(['roles.uid'=>$uid]);
                        })
                        ->get()
                        ->each(function($v,$k) {
                             $partition_name = HouseDistrict::where('id','=',$v->partition_id)->value('name');
                             $village_name = HouseDistrict::where('id','=',$v->village_id)->value('name');
                             $v->name_long = $village_name.$partition_name.$v->name_long;
                             unset($v->partition_id);
                             unset($v->village_id);
                        });
                    break;
               case 3:
                    $details = (new HouseDistrict)->parent($house_id)->reverse()->values();
                    $return[] = ['name_long'=>$details->pluck('name')->implode('')];
                    break;
               case 2:
                    $village_name = HouseDistrict::where('id','=',$house_id)->value('name');

                    $return=House::select('house.partition_id','house_district.name as name_long')
                        ->where(['village_id'=>$house_id])->groupBy('budding_id')
                        ->leftJoin('house_district','house_district.id','=','house.budding_id')
                        ->when($uid,function($query) use($uid){
                             $query->leftJoin('client_user_roles_house as roles','roles.house_id','=','house_district.id')->where(['roles.uid'=>$uid]);
                        })
                        ->get()
                        ->each(function($v,$k) use($village_name){
                         $partition_name = HouseDistrict::where('id','=',$v->partition_id)->value('name');
                         $v->name_long = $village_name.$partition_name.$v->name_long;
                         unset($v->partition_id);
                    });
                    break;
          }
          return $return;
     }
	/**
	 * 反馈时可选的印象标签
	 */
	public function house_manager_feedback_tags(){
		$tags = [
			['态度恶劣','答非所问','解决不了问题'],
			['回复太慢','不知道在忙什么','等太久了'],
			['一般一般','有待改善','回复有用'],
			['挺好的','问题解决','态度有待改善','没毛病'],
			['很热情','态度好','问题解决','是真爱'],
		];
		return json_success('OK',$tags);
	}
	
	/**
	 * @param ManagerFeedbackRequest $request
	 * @return array
	 * 业主对房管评价
	 */
	public function house_manager_feedback_submit(ManagerFeedbackRequest $request){
		$add = [
			'from_uid'	=> $this->uid,
			'to_uid'	=> $request->input('uid'),
			'star'		=> $request->input('star'),
			'tags'		=> implode(',',json_decode($request->input('tags'),true)) ?? '',
			'comment'	=> $request->input('comment'),
			'created_at'=> time2date(),
		];
		$id = ClientUserManagerFeedback::create($add)->id;
		// 给予评价赠送积分，评价星级决定了积分数量，比例1:1
		ClientUserIntegral::create()->data($request->input('uid'),3,$request->input('star'))->save();
		return json_return($id,'','评分已提交',['id'=>$id]);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 房屋管家聊天设置为已读，app每次进来都要请求接口
	 */
	public function house_manager_viewed(BasicRequest $request){
		$uid = $request->input('uid');
		$var = ClientUserRongcloud::where(['from_uid'=>$this->uid,'to_uid'=>$uid])->update(['viewed'=>1]);
		return json_success('消息阅读完成');
	}
	
	
	/**
	 * 消息类型列表
	 */
	public function message_type(Request $request){
		$cate = ClientUserMessagesType::get();
		$cate->each(function($v,$k){
			$v->unview_count = group99(ClientUserMessage::where(['uid'=>$this->uid,'type_id'=>$v->id,'viewed'=>0])->count());
			$latest = ClientUserMessage::where(['uid'=>$this->uid,'type_id'=>$v->id])->latest()->first();

			if($latest->content_id>0){
                    $latest->content=ClientUserMessagesContent::where(['id'=>$latest->content_id])->value('content');
               }

			$v->preview = str_limit($latest->content,30);
			$v->preview_time = $latest->created_at;
		});
		return json_success('OK',$cate);
	}
	
	/**
	 * 消息类型下的消息列表
	 */
	public function message_list(Request $request){
		$type_id = $request->input('type_id');
		$list = ClientUserMessage::select(DB::raw('client_user_messages.*,(case content_id when 0 then client_user_messages.content else content.content end) as content,(case content_id when 0 then client_user_messages.title else content.title end) as title'))
              ->leftJoin('client_user_messages_content as content','client_user_messages.content_id','=','content.id')
              ->where(['client_user_messages.type_id'=>$type_id])
              ->where(['uid'=>$this->uid])
              ->orderBy('client_user_messages.id','desc')
              ->pages();
		// 设置为已读
		ClientUserMessage::where(['type_id'=>$type_id,'uid'=>$this->uid])->update(['viewed'=>1]);
		return json_success('OK',$list);
	}
	
	/**
	 * 消息详情
	 */
	public function message_detail(Request $request){
		$id = $request->input('id');
		$data = ClientUserMessage::select(DB::raw('client_user_messages.*,(case content_id when 0 then client_user_messages.content else content.content end) as content,(case content_id when 0 then client_user_messages.title else content.title end) as title'))
              ->leftJoin('client_user_messages_content as content','client_user_messages.content_id','=','content.id')
              ->where(['id'=>$id])->first();
		return json_success('OK',$data);
	}
	
	/**
	 * @param Request $request
	 * 我的咨询
	 */
	public function advisory(Request $request){
	
	}
	
	/**
	 * @param Request $request
	 * 我的投诉
	 */
	public function complaints(Request $request){
	
	}
	
	/**
	 * @param Request $request
	 * 我的收藏
	 */
	public function favorite(Request $request){
	
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 我的收货地址
	 */
	public function address(BasicRequest $request){
	    $village_id = $request->input('village_id');
		$address = ClientUserAddress::where(['uid'=>$this->uid])
            ->when($village_id,function($query) use($village_id){
                $query->where(['village_id'=>$village_id]);
            })
            ->get()
            ->each(function($v,$k){
			$v->detail();
		});
		return json_success('OK',$address);
	}
	
	// 收货地址详情
	public function address_detail(BasicRequest $request){
		$id = $request->input('id');
		$address = ClientUserAddress::where(['uid'=>$this->uid,'id'=>$id])->first()->detail();
		return json_success('OK',$address);
	}
	
	public function address_add(AddressAddRequest $request){
		$add = $request->only(['realname','mobile','house_id','address','is_default']);
        $village_id = House::where(['house_id'=>$add['house_id']])->value('village_id');
        if(!$village_id){
            return json_error('找不到该房屋，请重试');
        }
        if($add['is_default']){

        }
        $add['village_id']=$village_id;
		$add['uid'] = $this->uid;
		$add['status'] = 1;
		if($add['is_default']){
            ClientUserAddress::where(['uid'=>$this->uid])->update(['is_default'=>0]);
        }
		$var = ClientUserAddress::create($add)->id;
		return json_return($var,'','添加成功',['id'=>$var]);
	}
	
	public function address_edit(AddressAddRequest $request){
		$add = $request->only(['realname','mobile','house_id','address','is_default']);
        $village_id = House::where(['house_id'=>$add['house_id']])->value('village_id');
        if(!$village_id){
            return json_error('找不到该房屋，请重试');
        }
        $add['village_id']=$village_id;
		$id = $request->input('id');
		$is_default = $request->input('is_default');
		// 如果获取到设置为默认，先把之前的全部设为不默认
		if($is_default){
			ClientUserAddress::where(['uid'=>$this->uid])->update(['is_default'=>0]);
		}
		$var = ClientUserAddress::where(['id'=>$id,'uid'=>$this->uid])->update($add);
		return json_return($var,'','修改成功',['id'=>$id]);
	}
	
	public function address_del(BasicRequest $request){
		$id = $request->input('id');
		$var = ClientUserAddress::where(['id'=>$id])->delete();
		return json_return($var,'','已删除收货地址');
	}
	
	
	/**
	 * @param Request $request
	 * @return array
	 * 我的发布
	 */
	public function neighbor(Request $request){
		// 0分享，1拼车，2租房，3二手，4社区活动
		$type = $request->input('type');
		$data = NeighborHelp::where(['uid'=>$this->uid,'neighbor_help.type'=>$type])->list()->pagesParse();
		return json_success('OK',$data);
	}
	
	
	/**
	 * @param PasswordResetRequest $request
	 * @return array
	 * @throws ApiException
	 * 修改密码
	 */
	public function password_reset(PasswordResetRequest $request){
		$clientUser = new ClientUser();
		$password_old = $request->input('password_old');
		$password_new = $request->input('password_new');
		$password_gen = $clientUser->passwordEncodeSalt($password_old,$this->user->salt);
		if(strcmp($password_gen,$this->user->password) !== 0){
			throw new ApiException('原密码输入错误');
		}
		$password_new_gen = $clientUser->passwordEncodeSalt($password_new,$this->user->salt);
		$var = ClientUser::where(['id'=>$this->uid])->update(['password'=>$password_new_gen]);
		return json_return($var,'','密码修改成功');
	}
}